package com.shouyun.modules.security.oauth2;

import com.alibaba.fastjson.JSONObject;
import com.shouyun.common.exception.ErrorCode;
import com.shouyun.common.utils.ConvertUtils;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.common.utils.DateUtils;
import com.shouyun.common.utils.MessageUtils;
import com.shouyun.modules.security.service.SysUserTokenService;
import com.shouyun.modules.security.user.UserDetail;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 认证
 *
 * @author Sunshouguo
 */
@Component
public class Oauth2Realm extends AuthorizingRealm {
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDetail user = (UserDetail) principals.getPrimaryPrincipal();

        //用户权限列表

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        JSONObject user = sysUserTokenService.getByToken(accessToken);
        JSONObject tokenList = DataUtils.getData(DataUtils.TOKEN);
        for (String tokenKey : tokenList.keySet()) {
            if (!tokenKey.equals(accessToken)) {
                JSONObject tokenUser = tokenList.getJSONObject(tokenKey);
                //30天不登录则过期
                if (tokenUser == null || tokenUser.getDate("lastDate") == null || DateUtils.addDateDays(tokenUser.getDate("lastDate"), 30).getTime() < System.currentTimeMillis()) {
                    sysUserTokenService.logout(tokenKey);
                }
            }
        }
        //token失效
        if (user == null || StringUtils.isBlank(user.getString("username"))) {
            sysUserTokenService.logout(accessToken);
            throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID));
        }
        UserDetail userDetail = new UserDetail();
        userDetail.setUsername(user.getString("username"));
        userDetail.setPassword(user.getString("password"));
        userDetail.setSuperAdmin(user.getInteger("superAdmin"));
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
        return info;
    }

}